package hot100.h0917;
/**
  * @description 计算二叉树的直径
  * @author 不知名帅哥
  * @date 2024/9/17 12:39
  * @version 1.0
*/
public class ComputeBinaryTreeDiameter {
    public static void main(String[] args) {

    }

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    private int maxDiameter=0;
    public int diameterOfBinaryTree(TreeNode root) {
        calculateDepth(root);
        return maxDiameter;
    }

    private int calculateDepth(TreeNode root) {
        if (root == null) return 0;

        int leftPath = calculateDepth(root.left);
        int rightPath = calculateDepth(root.right);

        maxDiameter = Math.max(maxDiameter, leftPath + rightPath);
        return Math.max(leftPath, rightPath) + 1;
    }
}
